var express=require("express");
var fs = require('fs');
var path = require('path');
var Mock = require('mockjs');
var chokidar = require('chokidar')
var router=express.Router();

function rescallback(filepath,callback) {
    console.log("[mock] "+filepath)
    fs.readFile(filepath,"utf8",function (err,data) {
        if(err) console.log(err)
        try{
            data = JSON.parse(data)

        }catch (e){
            data = {error:e}
            console.log(e.toString())
        }
        callback(Mock.mock(data))
    })
}

module.exports = function (app) {
    chokidar.watch("./data/*.json").on('add', (filepath) => {
        var filename = path.basename(filepath);
        var url= filename.split("_");
        var routerInfo = {method:"",url:""};
        url.forEach(function (part,index) {
            if(index==0){
                routerInfo.method = part
            }else if(index == url.length - 1){
                routerInfo.url = routerInfo.url + "/" + part.replace(".json","")
            }else{
                routerInfo.url = routerInfo.url + "/" + part
            }
        })

        if(routerInfo.method=="post"){
            router.post(routerInfo.url,function (req,res) {
                res.header("Access-Control-Allow-Origin", "*");
                rescallback(filepath,function (data) {
                    setTimeout(function () {
                        res.send(data)
                    },666)
                })
            })
        }
        if(routerInfo.method=="get"){
            router.get(routerInfo.url,function (req,res) {
                res.header("Access-Control-Allow-Origin", "*");
                rescallback(filepath,function (data) {
                    setTimeout(function () {
                        if(req.query.type=='string'){
                            res.send(JSON.stringify(data))
                        }else {
                            res.send(data)
                        }
                    },666)
                })
            })
        }


    })

    return router

};